<template>
  <div
    class="map-view"
    :class="{
      loading: loading,
      'full-screen': isFullScreen,
    }"
    :style="{ height }"
  >
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map-container"></div>

    <!-- 工具栏 -->
    <div v-if="showToolbar" class="map-toolbar">
      <el-button-group>
        <el-button @click="handleZoomIn">
          <el-icon><ZoomIn /></el-icon>
        </el-button>
        <el-button @click="handleZoomOut">
          <el-icon><ZoomOut /></el-icon>
        </el-button>
        <el-button @click="handleLocate">
          <el-icon><Aim /></el-icon>
        </el-button>
      </el-button-group>
    </div>

    <!-- 搜索框 -->
    <div v-if="showSearch" class="map-search">
      <el-autocomplete
        v-model="searchQuery"
        :fetch-suggestions="searchLocation"
        placeholder="搜索地点"
        :trigger-on-focus="false"
        @select="handleSelect"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-autocomplete>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-mask">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>地图加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import {
  Location,
  FullScreen,
  FullscreenExit,
  ZoomIn,
  ZoomOut,
  Search,
  Loading,
  Aim,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import AMapLoader from "@amap/amap-jsapi-loader";

const props = defineProps({
  center: {
    type: Array,
    default: () => [110.479191, 23.114274], // 贵港市中心坐标
  },
  zoom: {
    type: Number,
    default: 12,
  },
  height: {
    type: String,
    default: "400px",
  },
  markers: {
    type: Array,
    default: () => [],
  },
  showToolbar: {
    type: Boolean,
    default: true,
  },
  showSearch: {
    type: Boolean,
    default: true,
  },
  fitView: {
    type: Boolean,
    default: true,
  },
  interactive: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits([
  "update:center",
  "update:zoom",
  "marker-click",
  "map-click",
  "map-ready",
]);

// 状态变量
const mapContainer = ref(null);
const map = ref(null);
const loading = ref(true);
const isLocating = ref(false);
const isFullScreen = ref(false);
const searchQuery = ref("");
const markerInstances = ref([]);

// 地图实例
let mapInstance = null;

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: "your-amap-key", // 请替换为实际的高德地图 Key
      version: "2.0",
      plugins: ["AMap.ToolBar", "AMap.Scale", "AMap.Geolocation"],
    });

    mapInstance = new AMap.Map(mapContainer.value, {
      center: props.center,
      zoom: props.zoom,
      resizeEnable: true,
    });

    // 添加控件
    if (props.interactive) {
      mapInstance.addControl(new AMap.Scale());
    }

    // 绑定事件
    mapInstance.on("click", handleMapClick);
    mapInstance.on("moveend", handleMapMove);
    mapInstance.on("zoomend", () => {
      emit("update:zoom", mapInstance.getZoom());
    });

    // 添加标记点
    addMarkers();

    loading.value = false;
    emit("map-ready", mapInstance);
  } catch (error) {
    console.error("地图初始化失败:", error);
    ElMessage.error("地图初始化失败");
  }
};

// 添加标记点
const addMarkers = () => {
  // 清除现有标记
  markerInstances.value.forEach((marker) => marker.remove());
  markerInstances.value = [];

  // 添加新标记
  props.markers.forEach((markerData) => {
    const marker = new AMap.Marker({
      position: markerData.position,
      title: markerData.title,
      icon: markerData.icon,
      label: markerData.label
        ? {
            content: markerData.label,
            direction: "top",
          }
        : null,
    });

    marker.on("click", () => {
      emit("marker-click", markerData);
    });

    marker.setMap(mapInstance);
    markerInstances.value.push(marker);
  });

  // 自动调整视野
  if (props.fitView && markerInstances.value.length > 0) {
    mapInstance.setFitView();
  }
};

// 处理地图点击
const handleMapClick = (e) => {
  emit("map-click", {
    lnglat: [e.lnglat.getLng(), e.lnglat.getLat()],
  });
};

// 处理地图移动
const handleMapMove = () => {
  const center = mapInstance.getCenter();
  emit("update:center", [center.getLng(), center.getLat()]);
};

// 缩放控制
const handleZoomIn = () => {
  mapInstance.zoomIn();
};

const handleZoomOut = () => {
  mapInstance.zoomOut();
};

// 定位到当前位置
const handleLocate = () => {
  if (isLocating.value) return;
  isLocating.value = true;

  try {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
    });

    mapInstance.addControl(geolocation);

    geolocation.getCurrentPosition((status, result) => {
      if (status === "complete") {
        mapInstance.setCenter(result.position);
        ElMessage.success("定位成功");
      } else {
        console.error("定位失败");
        ElMessage.error("定位失败，请检查定位权限");
      }
    });
  } catch (error) {
    console.error("定位失败:", error);
  } finally {
    isLocating.value = false;
  }
};

// 切换全屏
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value;
  if (isFullScreen.value) {
    document.body.style.overflow = "hidden";
  } else {
    document.body.style.overflow = "";
  }
  // 触发地图重新渲染
  setTimeout(() => {
    mapInstance.resize();
  }, 100);
};

// 搜索地点
const searchLocation = async (query, callback) => {
  if (!query) {
    callback([]);
    return;
  }

  try {
    const autoComplete = new AMap.AutoComplete({
      city: "贵港市",
    });

    const result = await new Promise((resolve, reject) => {
      autoComplete.search(query, (status, result) => {
        if (status === "complete") {
          resolve(result.tips);
        } else {
          reject(result);
        }
      });
    });

    callback(
      result.map((item) => ({
        value: item.name,
        location: item.location,
      })),
    );
  } catch (error) {
    console.error("搜索失败:", error);
    callback([]);
  }
};

// 处理地点选择
const handleSelect = (item) => {
  if (item.location) {
    mapInstance.setCenter([item.location.lng, item.location.lat]);
    mapInstance.setZoom(15);
  }
};

// 生命周期钩子
onMounted(() => {
  initMap();
});

onUnmounted(() => {
  if (mapInstance) {
    mapInstance.destroy();
  }
});

// 监听属性变化
watch(
  () => props.markers,
  () => {
    if (mapInstance) {
      addMarkers();
    }
  },
  { deep: true },
);

watch(
  () => props.center,
  (newCenter) => {
    if (mapInstance && newCenter) {
      mapInstance.setCenter(newCenter);
    }
  },
);

watch(
  () => props.zoom,
  (newZoom) => {
    if (mapInstance && newZoom) {
      mapInstance.setZoom(newZoom);
    }
  },
);
</script>

<style lang="scss" scoped>
.map-view {
  @apply relative w-full;

  &.full-screen {
    @apply fixed inset-0 z-50 bg-white;

    .map-container {
      @apply h-screen;
    }
  }

  .map-container {
    @apply w-full rounded-lg overflow-hidden;
  }

  .map-toolbar {
    @apply absolute top-4 right-4 z-10;

    .el-button-group {
      @apply bg-white shadow-md rounded-lg overflow-hidden;
    }
  }

  .map-search {
    @apply absolute top-4 left-4 w-64;

    :deep(.el-input__wrapper) {
      @apply bg-white shadow-lg;
    }
  }

  .loading-mask {
    @apply absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-90;

    .loading-icon {
      @apply text-2xl text-primary-600 animate-spin mb-2;
    }
  }
}
</style>
